package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Employee employee, Long[] ids) {
        //对密码进行加密(把用户名当做盐)
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);
        //关联关系
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        Employee employee1 = employeeMapper.selectByPrimaryKey(employee.getId());
        String password = employee1.getPassword();
        employee.setPassword(password);
        employeeMapper.updateByPrimaryKey(employee);
        employeeMapper.deleteRelation(employee.getId());
        //关联关系
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public Employee select(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    //调用Mapper接口的实现类对象的方法查询数据，封装成PageResult对象返回
    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo(employees);
    }

    @Override
    public Employee login(String username, String password) {
        //查询数据库中是否有匹配的数据
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            //通知调用者出现异常
            throw  new RuntimeException("账号和密码不匹配");
        }
        return employee;
    }

    @Override
    public boolean updatePwd(Employee employee, String oldPassword, String newPassword) {
        Md5Hash md5Hash = new Md5Hash(oldPassword, employee.getName());
        if (md5Hash.toString().equals(employee.getPassword())) {
            Md5Hash md5Hash2 = new Md5Hash(newPassword, employee.getName());
            employee.setPassword(md5Hash2.toString());
            employee.setDept(departmentMapper.selectByPrimaryKey(employee.getDept_id()));
            employeeMapper.updateByPrimaryKey(employee);
            return true;
        } else {
            throw new RuntimeException("原密码不正确");
        }
    }

    @Override
    public void resetPwd(Long id, String newPassword) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        Md5Hash md5Hash = new Md5Hash(newPassword, employee.getName());
        employee.setPassword(md5Hash.toString());
        employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);

        //删除中间表的数据
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public void resetStatus(Employee employee) {
        employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public Workbook exportXls() {
        //获取所有员工
        List<Employee> employees = employeeMapper.selectAll();
        //创建一个execl对象
        Workbook workbook = new HSSFWorkbook();
        //创建一页纸
        Sheet sheet = workbook.createSheet("员工通讯录");
        //创建标题行
        Row row = sheet.createRow(0);
        //创建单元格（穿入列，索引从0），在单元格上写内容
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        //便利获取每一个员工
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建一行（索引从0）
            row = sheet.createRow(i+1);
            //在单元格上写内容
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            if (employee.getAge() != null) {
                row.createCell(2).setCellValue(employee.getAge());
            }

        }
        return workbook;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读execl文件
        Workbook workbook = new HSSFWorkbook(file.getInputStream());
        //读哪一页
        Sheet sheet = workbook.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();

        for (int i = 1; i < lastRowNum; i++) {
            //获取每一行
            Row row = sheet.getRow(i);
             //创建员工对象
            Employee employee = new Employee();
            String name = row.getCell(0).getStringCellValue();
            employee.setName(name);
            String email = row.getCell(1).getStringCellValue();
            employee.setEmail(email);

            //设置单元格类型
//            row.getCell(2).setCellType(CellType.STRING);//数值类型解决方法

            //判断单元格类型
            CellType cellType = row.getCell(2).getCellType();
            if (cellType.equals(CellType.STRING)) {
                String age = row.getCell(2).getStringCellValue();//字符串方法
                employee.setAge(Integer.valueOf(age));
            } else {
                double value = row.getCell(2).getNumericCellValue();//数值类型解决方法2
                employee.setAge((int) value);//数值类型解决方法2
            }

            employee.setPassword("1");
            //插入数据库
            this.insert(employee,null);
        }

    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }
}
